//
//  SLLoginVC.swift
//  sulit-loan
//
//  Created by 王刚锋 on 2025/4/5.
//  Copyright © 2025 coolBoy. All rights reserved.
//

import UIKit
import MBProgressHUD

class SLLoginVC: SLBaseVC {
    private var phoneTF:UITextField?
    private var codeTF:UITextField?
    private var codeBtn:UIButton?
    private var countdownTimer: Timer?
    private var countdown = 0
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "Login"
        let Welcome = create_label(text: "Welcome ", textColor: .black, textFont: SLFontConfig.medium(size: 24), supView: self.view, closure: { make in
            make.left.equalTo(27)
            make.top.equalTo(self.navigationView.snp.bottom).offset(40)
            make.height.equalTo(34)
        })
        let hand = create_imageView(image: IMAGE("icon_hand"), mode: .scaleAspectFill, supView: self.view) { make in
            make.left.equalTo(Welcome.snp.right).offset(8)
            make.width.height.equalTo(24)
            make.centerY.equalTo(Welcome.snp.centerY)
        }
        let phoneView = create_view(bgColor: rgba(hex: "#F3F6F9"), supView: self.view) { make in
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.top.equalTo(Welcome.snp.bottom).offset(74)
            make.height.equalTo(48)
        }
        let numL = create_label(text: "+63 ", textColor: .black, textFont: SLFontConfig.regular16,alignment: .center, supView: phoneView, closure: { make in
            make.left.top.bottom.equalTo(0)
            make.width.equalTo(50)
        })
        let num = __valueForKey(key: kNum) as! String
        numL.text = "+" + num
        let line = create_view(bgColor: rgba(hex: "#D5E5F5"), supView: phoneView) { make in
            make.width.equalTo(1)
            make.height.equalTo(32)
            make.left.equalTo(50)
            make.centerY.equalToSuperview()
        }
        
        let phoneT = create_textField(text: "", textColor: .black, textFont: SLFontConfig.medium15,place: "Please enter your phone number", supView: phoneView ) { make in
            make.left.equalTo(60)
            make.right.equalTo(-10)
            make.top.bottom.equalTo(0)
        }
        phoneT.keyboardType = .numberPad
        phoneTF = phoneT
        
        let codeView = create_view(bgColor: rgba(hex: "#F3F6F9"), supView: self.view) { make in
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.top.equalTo(phoneView.snp.bottom).offset(30)
            make.height.equalTo(48)
        }
        let codeT = create_textField(text: "", textColor: .black, textFont: SLFontConfig.medium15,place: "Please enter the code", supView: codeView ) { make in
            make.left.equalTo(16)
            make.right.equalTo(-100)
            make.top.bottom.equalTo(0)
        }
        codeT.keyboardType = .numberPad
        codeTF = codeT

        let codeBtn = create_button(title: "Get Code", titleColor: rgba(hex: "#1608EC"), titleFont: SLFontConfig.regular14,image: nil,supView: codeView, closure: { make in
            make.right.equalTo(-16)
            make.top.bottom.equalTo(0)
        }, selector: (target: self, action: #selector(getCode), event: .touchUpInside))
        self.codeBtn = codeBtn

        let volBtn = create_button(title: "VOZ?", titleColor: rgba(hex: "#1608EC"), titleFont: SLFontConfig.regular16, image: IMAGE("icon_VOZ"), supView: self.view, closure: { make in
            make.right.equalTo(-15)
            make.top.equalTo(codeView.snp.bottom).offset(10)
            make.height.equalTo(24)
        }, selector: (target: self, action:#selector(volAction), event: .touchUpInside))
                  
        view.addSubview(loginButton)
        loginButton.snp.makeConstraints { make in
            make.width.equalTo(281)
            make.height.equalTo(44)
            make.top.equalTo(codeView.snp.bottom).offset(95)
            make.centerX.equalToSuperview()
        }
                
        let agreementStack = UIStackView(arrangedSubviews: [agreementCheckbox, agreementLabel])
        agreementStack.spacing = 8
        agreementStack.alignment = .center
        agreementStack.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(agreementStack)
        agreementStack.snp.makeConstraints { make in
            make.top.equalTo(loginButton.snp.bottom).offset(6.5)
            make.centerX.equalToSuperview()
        }
        agreementCheckbox.isSelected = true
        updateLoginButtonState()
    }
     lazy var loginButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Login", for: .normal)
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18)
        button.setTitleColor(.white, for: .normal)
        button.backgroundColor = rgba(hex: "#747474", a: 0.24)
        button.layer.cornerRadius = 22
        button.isEnabled = false
        button.addTarget(self, action: #selector(loginAction), for: .touchUpInside)

        button.translatesAutoresizingMaskIntoConstraints = false
        return button
       }()
    lazy var agreementCheckbox: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(IMAGE("signin_icon_select"), for: .normal)
        button.setImage(IMAGE("signin_icon_selected"), for: .selected)
        button.tintColor = rgba(hex: "#1608EC")
        button.translatesAutoresizingMaskIntoConstraints = false
        button.addTarget(self, action: #selector(agreementCheckboxTapped), for: .touchUpInside)
        return button
       }()
       
    lazy var agreementLabel: UILabel = {
           let label = UILabel()
           let text = "I have read and agree Privacy Agreement"
           label.text = text
           label.font = UIFont.systemFont(ofSize: 14)
           label.textColor = .gray
           label.translatesAutoresizingMaskIntoConstraints = false
           
           // 设置部分文本带下划线
           let attributedString = NSMutableAttributedString(string: "I have read and agree Privacy Agreement")
           let range = text.range(of: "Privacy Agreement")
           let startIndex = text.distance(from: text.startIndex, to: range!.lowerBound)
            let length = range!.upperBound.utf16Offset(in: text) - range!.lowerBound.utf16Offset(in: text)
           let rangeNs = NSRange(location: startIndex, length: length)

           attributedString.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: rangeNs)
           attributedString.addAttribute(.foregroundColor, value: rgba(hex: "#1608EC"), range: rangeNs)
           
           label.attributedText = attributedString
           // 添加点击手势
           label.isUserInteractionEnabled = true
           let tapGesture = UITapGestureRecognizer(target: self, action: #selector(agreementClick))
           label.addGestureRecognizer(tapGesture)
           
           return label
       }()
       

    @objc func agreementClick(){
        let url = __valueForKey(key: KProtocol)
        jump(url: url as? String )
    }
    @objc private func getCode(){
        // 验证手机号
        guard let phone = self.phoneTF!.text, !phone.isEmpty else {
            showAlert(message: "Please enter your phone number")
            return
        }
        let mbp = MBProgressHUD.showMessage(message: "")
        SLHttpTool.AsyncReportData(path: "/satisfies/somewhere",params: ["unquestionably":phone], target: self) { responseData, success, msg, code in
            mbp.hide(animated: true)
            MBProgressHUD.showSuccess(success: msg)
            if success{
                self.codeTF?.becomeFirstResponder()
                self.countdownAction()
            }
            
            // 这里添加获取验证码的网络请求
            print("Getting verification code for phone: \(phone)")
        }
        
    }
    private func countdownAction(){
        // 开始倒计时
        self.countdown = 60
        self.codeBtn!.setTitle("60s", for: .normal)
        self.codeBtn!.isEnabled = false
        self.codeBtn!.setTitleColor(.gray, for: .disabled)
        
        self.countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.updateCountdown), userInfo: nil, repeats: true)
    }
    @objc private func loginAction(){
        guard let phone = phoneTF!.text, !phone.isEmpty else {
            showAlert(message: "Please enter your phone number")
            return
        }
        guard let code = codeTF!.text, !code.isEmpty else {
            showAlert(message: "Please enter the verification code")
            return
        }
        
        // 这里添加登录逻辑
        print("Logging in with phone: \(phone), code: \(code)")
        SLHttpTool.AsyncReportData(path: "/satisfies/sculptor",params: ["finish":phone,"chunar":code], target: self) { responseData, success, msg, code in
            if success {
                __setValue(value: responseData["wavelets"]["splendour"].stringValue, key: KSessionId)
                let startTime = "\(self.startDate)"
                SLHttpTool.AsyncUploadData(mahathat: "1",thais:startTime, target: self) { responseData, success, msg, code in
                    
                }
                NotificationCenter.default.post(name: NSNotification.Name(loginInEvent), object: nil)
                self.dismiss(animated: true)
            }else{
                
            }
        }
    }
    @objc private func volAction(){
        guard let phone = phoneTF!.text, !phone.isEmpty else {
            showAlert(message: "Please enter your phone number")
            return
        }
       let mbp  = MBProgressHUD.showMessage(message: "")
        SLHttpTool.AsyncReportData(path: "/satisfies/imitation",params: ["unquestionably":phone], target: self) { responseData, success, msg, code in
            mbp.hide(animated:  true)
            MBProgressHUD.showSuccess(success: msg)
            if success{
                self.codeTF?.becomeFirstResponder()
            }
        }
    }
    
    @objc private func updateCountdown() {
        countdown -= 1
        if countdown > 0 {
            codeBtn!.setTitle("\(countdown)s", for: .normal)
        } else {
            countdownTimer?.invalidate()
            countdownTimer = nil
            codeBtn!.setTitle("Get Code", for: .normal)
            codeBtn!.isEnabled = true
        }
    }

    
    @objc private func agreementCheckboxTapped() {
        agreementCheckbox.isSelected = !agreementCheckbox.isSelected
        updateLoginButtonState()
    }
    
    private func updateLoginButtonState() {
        loginButton.isEnabled = agreementCheckbox.isSelected
        loginButton.backgroundColor = agreementCheckbox.isSelected ? rgba(hex: "#1608EC") : rgba(hex: "#747474", a: 0.24)
    }
    
    private func showAlert(message: String) {
        let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
        present(alert, animated: true, completion: nil)
    }

}
